package com.xxxx.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.server.mapper.MenuMapper;
import com.xxxx.server.mapper.MenuRoleMapper;
import com.xxxx.server.mapper.RoleMapper;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.Menu;
import com.xxxx.server.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhoubin
 * @since 2020-10-15
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

	@Resource
	private MenuMapper menuMapper;

	@Resource
    private MenuRoleMapper menuRoleMapper;

	@Resource
    private RoleMapper roleMapper;
	@Autowired
	private RedisTemplate<String,Object> redisTemplate;

	/**
	 * 根据当前用户获取菜单
	 *
	 * @return
	 */
	@Override
	public List<Menu> getMenusByAdminId() {

		Integer id = ((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
		List<Menu> menus = menuMapper.getMenusByAdminId(id);
		ValueOperations<String, Object> ops = redisTemplate.opsForValue();
		ops.set("menu:" + id,menus);
		return menus;
	}


	/**
	 * 查询所有菜单及对应角色
	 *
	 * @return
	 */
	@Override
	public List<Menu> getMenusWithRoles() {
		return menuMapper.getMenusWithRoles();
	}

    /**
     * 通过角色id查询菜单
     * @param id
     * @return
     */
    @Override
    public List<Menu> getmenuByRoleId(int id) {
        Assert.isTrue(id > 0 ,"不合法");
        return menuMapper.getmenuByRoleId(id);
    }



}
